<template>
  <el-dialog
    :title="formData.id?'编辑房产':'添加房产'"
    :visible="dialogVisible"
    width="46%"
    @close="closeFn"
  >
    <!-- 正文 -->
    <el-form ref="form" :model="formData" label-width="80px" :rules="rules">
      <el-form-item label="经纪" prop="agent">
        <el-select v-model="formData.agent" placeholder="请选择经纪">
          <el-option v-for="item in agentList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="formData.category" placeholder="请选择分类">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-tag
          v-for="(item,index) in formData.tags"
          :key="index"
          closable
          :disable-transitions="false"
          @close="handleClose(item)"
        >
          {{ item }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-row type="flex">
          <el-cascader
            :options="options"
            :value="formData.address"
            @change="cityChange"
          />
          <el-input v-model="formData.address" />
        </el-row>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" autosize />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="formData.content" type="textarea" autosize />
      </el-form-item>
      <el-form-item label="介绍图片" prop="photos">
        <imageUpload ref="photos" :limit="5" />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <imageUpload ref="image" :limit="1" />
      </el-form-item>

    </el-form>

    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { agentsList } from '@/api/agents' // 获取经纪列表
import { category } from '@/api/category' // 获取分类列表
import { addProperty, getPropertyDetail, editPropertyDetail } from '@/api/property' // 房产api
import { getData1 } from './property_api'

import imageUpload from './imaUpload.vue'

export default {
  components: { imageUpload },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    propertyId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      // 行政区划
      options: [],
      optionData: '',
      // 表单
      formData: {
        agent: '', // 经纪
        category: null, // 分类
        title: '', // 标题
        tags: [], // 标签
        address: '', // 地址
        price: null, // 价格
        desc: '', // 描述
        content: '', // 内容 列表里的介绍
        photos: [], // 图片
        image: '' // 封面
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '表述不能为空', trigger: 'blur' },
          { max: 500, message: '标题不能超过500个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '表述不能为空', trigger: 'blur' },
          { max: 500, message: '标题不能超过500个字符', trigger: 'blur' }
        ]
      },
      agentList: [], // 经纪列表
      categoryList: [], // 分类列表
      title: '', // 弹窗标题
      // 标签相关的
      inputVisible: false,
      inputValue: ''
    }
  },
  async created() {
    // 编辑回显
    if (this.propertyId) {
      // 回显基本数据
      this.formData = await getPropertyDetail(this.propertyId)
      // 回显封面
      this.$refs.image.fileList.push({ url: this.formData.image })
      // 回显照片
      this.formData.photos.forEach(item => {
        this.$refs.photos.fileList.push({ url: item })
      })
      // 内容去标签
      this.formData.content = this.formData.address.innerHTML
    }

    // console.log(this.formData)
    // 分类和经纪数据
    this.agentList = await agentsList()
    this.categoryList = await category()

    // 行政区域
    this.getProvince()

    // this.getAllData(province)
  },
  methods: {
    // 获取省份
    async getProvince() {
      const res = await getData1({
        Key: '62e068ffa796be473df4cb5d41c1cccf',
        subdistrict: 3
      })
      const list = res.data.districts[0].districts
      // console.log('行政区划数据', list)
      // const data = this.dataToTree(list)
      // console.log('测试', data)
      this.options = this.dataToTree(list)
    },

    dataToTree(list) {
      const arr = []
      list.forEach(item => {
        const obj = {}

        obj.value = item.name
        obj.label = item.name
        // obj.children = []
        obj.children = [...this.dataToTree(item.districts)]
        if (item.districts.length === 0) {
          delete obj.children
        }

        arr.push(obj)
      })
      return arr
    },

    // 取消按钮
    closeFn() {
      // 清空表单
      this.formData = {
        agent: '', // 经纪
        category: null, // 分类
        title: '', // 标题
        tags: [], // 标签
        address: '', // 地址
        price: null, // 价格
        desc: '', // 描述
        content: '', // 内容 列表里的介绍
        photos: [], // 图片
        image: '' // 封面
      }
      // 清空校验规则
      this.$refs.form.resetFields()
      // 清除父组件的id
      this.$emit('update:propertyId', null)
      // 关闭弹窗
      this.$emit('update:dialogVisible', false)
      // console.log('closeFn')
    },

    // 确定按钮
    async confirmFn() {
      try {
        if (this.formData.id) { // 编辑
        // console.log(this.formData.id)
          await this.$refs.form.validate()
          await editPropertyDetail(this.formData)
          this.$message.success('编辑成功')
        } else { // 新增
        // 处理弹窗里面的数据
          if (this.$refs.image.fileList.length > 0) {
            this.formData.image = this.$refs.image.fileList[0].url
          }
          if (this.$refs.photos.fileList.length > 0) {
            const photos = this.$refs.photos.fileList
            photos.forEach(item => {
              this.formData.photos.push(item.url)
            })
          }
          // 处理"描述"里面的数据
          this.formData.content = '<p>' + this.formData.content + '</p>'
          // 表单验证
          await this.$refs.form.validate()
          // 发送请求
          await addProperty(this.formData)
          this.$message.success('添加成功')
        }

        // 刷新列表
        this.$emit('getList')
        this.closeFn()
      } catch (error) {
        console.log(error)
      }
    },

    // 标签组件相关 ------------------------
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus('')
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 标签组件相关 ------------------------

    // 行政区划
    cityChange(data) {
      // console.log(data)
      this.formData.address = data.join(' ')
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
